package service

import (
	file2 "LogisticsPort/file"
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"LogisticsPort/utils"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"time"
)

func File(r *gin.Engine) {
	file := r.Group("/file/:module")
	{
		file.POST("/save", filesSave)
		file.GET("/delete", fileDelete)
		file.GET(sql.RequestList, filesList)
	}
}

func filesList(c *gin.Context) {
	sql.HttpHandle("文件获取", c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var list []model.FileInfo
		module := c.Param("module") //模块
		fileType := c.Query("type") //属性
		identification := c.Query("identification")
		if identification == "" || module == "" {
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}
		if fileType != "" {
			db = db.Where("type = ?", fileType)
		}
		db = db.Where("identification = ?", identification)
		db.Find(&list)
		return db, list
	})
}

func filesSave(c *gin.Context) {
	sql.HttpHandle("文件保存", c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		module := c.Param("module")                    //（二级目录）模块：采购、商品、...
		folder := "./upload" + "/" + module + "/"      //（三级级目录）文件夹
		identification := c.PostForm("identification") //唯一标识
		fileType := c.PostForm("type")                 //类型：手续、账单...
		fileName := c.PostForm("fileName")             //文件名称

		//多级目录
		if childFolder := c.PostForm("folder"); childFolder != "" {
			folder = folder + childFolder + "/"
		}
		//创建文件
		if err := utils.CreateDir(folder); err != nil {
			db.Error = err
			return db, nil
		}

		form, err := c.MultipartForm()
		if err != nil {
			db.Error = err
			return db, nil
		}

		files := form.File["files[]"]
		if identification == "" || files == nil {
			db.Error = errors.New(sql.ErrorParams)
			return db, nil
		}
		var list []file2.FileBean
		for _, file := range files {
			if len(files) > 1 || (len(files) == 1 && fileName == "") {
				fileName = file.Filename
			}
			var fileBean = file2.FileBean{
				CreateTime:     time.Now().Format("2006-01-02 15:04:05"),
				Identification: identification,
				Module:         module,
				Type:           fileType,
				Name:           fileName,
				Path:           folder + fileName,
			}
			fmt.Println(fileBean.Path)
			db, newFile := fileBean.FileSave(c, db, file)
			if db.Error != nil {
				return db, nil
			}
			list = append(list, *newFile)
		}
		return db, list
	})
}

func fileDelete(c *gin.Context) {
	sql.HttpDeleteById(c, &model.FileInfo{})
}
